package com.dhj.jvmstudy.chapter08;

import java.lang.ref.WeakReference;

/**
 * 弱引用测试：发现即回收
 * -XX:+PrintGCDetails
 */
public class WeakReferenceTest {

    public static class User {
        public int id;
        public String name;

        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User[id=" + id + ", name='" + name + "]";
        }
    }

    public static void main(String[] args) {
        // 创建对象，建立弱引用
        WeakReference<User> user = new WeakReference<>(new User(1, "dahuajia"));
        // 从弱引用中重新获得强引用对象
        System.out.println(user.get());

        System.gc();
        System.out.println("After GC: ");
        // 垃圾回收之后获得弱引用中的对象
        System.out.println(user.get());

    }


}
